
// "msg" : keycode[77,83,71]
//
var serice_keytypes = [];


$("#cmd").keydown(function(evt){
	serice_keytypes.push(String.fromCharCode(evt.which));
	
	tmp = serice_keytypes.join("").toLowerCase();
	console.log(tmp);
	if (tmp.endsWith("msg")){
        value = $("#info-cmd")[0].textContent;

        if (value != "msg"){
            show_cmd_info("msg");
            serice_keytypes = [];    
        }
		
	}else if (tmp.endsWith("cmd")){
		show_cmd_info("cmd");
		serice_keytypes = [];
	}else if (tmp.endsWith("servers")){
		show_cmd_info("servers");
		serice_keytypes = [];
	}else if (tmp.endsWith("search")){
		show_cmd_info("search");
		serice_keytypes = [];
	}else if (serice_keytypes.length > 20){
		serice_keytypes = [];
	}else if (evt.which == 13){
        send();
    }
});


var show_cmd_info = function(info){
	$("#cmd").popover("hide");
	$("#cmd-btn").animate({
		"opacity":"0"
	},"fast");
	$("#info-cmd").text(info);
	$("#cmd").animate({
		"width":"300px"
	},"fast",
	function(){
		$("#cmd")[0].value = "";
		if (info == "msg"){
			$("#cmd").attr({
				"placeholder":">name:msg"
			});
			$("#cmd-btn").animate({
				"opacity":"1"
			},"fast");
		}else if (info == "servers"){
			$("#info-cmd").attr({
				"class":"input-group-addon glyphicon glyphicon-cloud"
			});
			$.postJSON(
				"/search",
				{"obj":'{"type":"servers"}'},
				function(data){
					obj = JSON.parse(data);
					$("#cmd").attr({
								"data-toggle":"popover",
								"data-placement":"right",
								"data-content":obj.res.join(" ")
						});

				});
		}else if (info == "search"){
			$.postJSON(
				"/search",
				{"obj":'{"type":"search"}'},
				function(data){
						obj = JSON.parse(data);
						console.log("search got ");
						$("#cmd").attr({
								"data-toggle":"popover",
								"data-placement":"right",
								"data-content":obj.res.join(" ")
						});

						$("#cmd").animate({
							"width":"100px"
						},
						"fast").popover(
							"show"
						);
				});
		}else if (info =="cmd"){
			$("#cmd-btn").animate({"opacity":"1","width":"200px"},"fast");
		}
	});
	
}

var send = function() {
        data_raw = $("#cmd").val().split(":");
        to = data_raw[0];
       	msg = data_raw[1];
       	parm_obj = {
       		"type":"msg",
  	     	"from": name,
    	    		"msg":msg,
        		"to":to
    		}

       	$.postJSON(
       		'/sendajaxmsg',
       		{
       			'obj':JSON.stringify(parm_obj)
       		},function(data){
                obj = JSON.parse(data);
                console.log(obj.res);
                $("#cmd").attr({
                    "data-content":obj.res
                });
                $("#cmd").popover("show");

       			// old = $("#send_0");
       			// old.attr({"id":"old"});
       			// old.before('<p class="alert alert-success" id="send_0">send ok </p>');
       		}
       	);
       }
